package com.design01_builder.pattern05_prototype.shallowcloneanddeepclone;

import org.junit.Test;

import java.io.*;

/**
 * @ClassName Test
 * @Description TODO
 * @Author zhangjunhao
 * @DATE 2023/9/3 12:22
 */
public class PrototypeTest {


    //浅克隆
    @Test
    public void test01() throws CloneNotSupportedException {
        ConcretePrototype c1 = new ConcretePrototype();
        ConcretePrototype c2 = c1.clone();

        System.out.println("对象c1和c2是同一个对象？" + (c1 == c2));
        //false

    }


    //浅的克隆
    @Test
    public void test02() throws CloneNotSupportedException {

        ConcretePrototype2 concretePrototype2 = new ConcretePrototype2();
        Person person = new Person();
        concretePrototype2.setPerson(person);

        ConcretePrototype2 clone = concretePrototype2.clone();
        Person person2 = clone.getPerson();
        person2.setName("zhangjunhao");

        //判断p1与p2是否是同一对象
        System.out.println("p1和p2是同一个对象？" + (person == person2));
        concretePrototype2.show();
        clone.show();
        //p1和p2是同一个对象？true
        //嫌疑人姓名: zhangjunhao
        //嫌疑人姓名: zhangjunhao

    }

    //深克隆
    /**
    * 如果想要进行深拷贝需要使用到对象序列化流
    * (对象序列化之后,再进行反序列化获取到的是不同对象)
    * */
    @Test
    public void test03() throws IOException, ClassNotFoundException {
        ConcretePrototype2 concretePrototype2 = new ConcretePrototype2();
        Person person = new Person("zhangjunhao");
        concretePrototype2.setPerson(person);


        //创建对象序列化输出流
        ObjectOutputStream oos = new ObjectOutputStream(new
                FileOutputStream("c.txt"));

        oos.writeObject(concretePrototype2);
        oos.close();

        //创建对象序列化输入流
        ObjectInputStream ois = new ObjectInputStream(new
                FileInputStream("c.txt"));
        //读取对象
        ConcretePrototype2 clone = (ConcretePrototype2) ois.readObject();
        Person person2 = clone.getPerson();
        person2.setName("sunhanbing");


        //判断p1与p2是否是同一个对象
        System.out.println("p1和p2是同一个对象?" + (person == person2));
        concretePrototype2.show();
        clone.show();
        //p1和p2是同一个对象？false
        //嫌疑人姓名: zhangjunhao
        //嫌疑人姓名: sunhanbing

    }


}
